import DingInfo from "../config";
import { BaseErr, util } from "utils";
const sameDay = (d1: Date, d2: Date) => {
    return (
        d1.getFullYear() === d2.getFullYear() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getDate() === d2.getDate()
    );
};
// 转对象
function formatter2Obj(content: string | object): object | null {
    if (util.nilValue(content)) {
        return null;
    }
    let jsonObj: object | null = null;
    if (typeof content === "string") {
        try {
            jsonObj = JSON.parse(content);
        } catch (error) {}
    } else if (typeof content === "object") {
        jsonObj = content;
    }
    return jsonObj;
}

// 到到顶部那一栏
function getTopRowData(rowArray: any[]): number | null {
    let topRowIndex = rowArray.findIndex((e) => {
        let tmpArr = Array.isArray(e) ? e : [];
        let third = tmpArr[2];
        if (Array.isArray(third) && third.length >= 1) {
            let first = third[0];
            if (Array.isArray(first) && first.length >= 2) {
                let txt = first[1].value;
                // 转一下 字符串
                txt = `${txt}`;
                return txt.indexOf("组别") >= 0;
            }
        }
        return false;
    });
    if (topRowIndex >= 0) {
        return topRowIndex;
    }
    return null;
}

// 找到 今天是 第几列
function findTodayIndex(topRow: any[], today: Date): number | null {
    let third = topRow[2];
    let thirdArr = Array.isArray(third) ? third : [];

    let matchIndex = thirdArr.findIndex((e) => {
        let tmpArr = Array.isArray(e) ? e : [];
        let valueObj = tmpArr[1] || {};
        let { value } = valueObj;
        if (typeof value === "number") {
            // 找日期
            let baseDate = new Date(1900, 0, 0);
            baseDate.setDate(baseDate.getDate() + value - 1);
            return sameDay(today, baseDate);
        }
        return false;
    });
    if (matchIndex >= 0) {
        return matchIndex;
    }
    return null;
}

// 递归找 内容
function runloopGetInput(dataArr: any[]): string | null {
    let result: string | null = null;
    let currentSearch = dataArr;
    while (util.nilValue(result)) {
        let isRight = false;
        if (Array.isArray(currentSearch)) {
            let third = currentSearch[2];
            if (Array.isArray(third)) {
                isRight = true;
                currentSearch = third;
            } else if (typeof third === "string") {
                result = third;
                isRight = true;
            }
        }
        if (!isRight) {
            return null;
        }
    }
    return result;
}

// 获取内部文本
function getInput(valueObj: { [k: string]: any }) {
    let { value } = valueObj || {};
    if (typeof value === "string") {
        return value;
    }
    if (typeof value === "object") {
        if (Array.isArray(value.data)) {
            let input = runloopGetInput(value.data);
            if (input) {
                return input;
            }
        }
    }
    return "__不知道__";
}

// 从数组中 , 找到对应的index的 value值
function findTargetValue(dataArray: any[], index: number) {
    for (let i = 0; i < dataArray.length; i++) {
        let item = dataArray[i];
        if (Array.isArray(item) && item.length >= 2) {
            let curIndex = item[0];
            if (typeof curIndex === "number" && curIndex <= index) {
                if (curIndex === index) {
                    return getInput(item[1]);
                }
            } else {
                return "__空数据__";
            }
        }
    }
}

// 格式化 组 数据了
function formatterGroupData(rowArray: any[], topRowIndex: number, todayIndex: number) {
    let personDataList = rowArray.slice(topRowIndex + 1);
    // 总数据
    let groups: { des: string; list: any[] }[] = [];
    // 上一个分组
    let lastGroup: { des: string; list: any[] } | null = null;

    // 遍历
    for (let i = 0; i < personDataList.length; i++) {
        let item = personDataList[i];
        let compareArr: any[] | null = null;
        if (
            Array.isArray(item) &&
            item.length >= 3 &&
            Array.isArray(item[2]) &&
            item[2].length > 0
        ) {
            compareArr = item[2];
        }
        if (!compareArr) {
            continue;
        }
        // 判断第一个是不是 组别
        let first = compareArr[0];
        if (Array.isArray(first) && first.length >= 2) {
            let innerIndex = first[0];
            if (innerIndex === 0) {
                // 是组啊
                let groupName = getInput(first[1]);
                lastGroup = { des: groupName, list: [] };
                groups.push(lastGroup);
            }
        }

        if (lastGroup) {
            let name = findTargetValue(compareArr, 2);
            let input = findTargetValue(compareArr, todayIndex);
            lastGroup.list.push({
                name,
                input: input || "", // 可能今天没有填写...
            });
        }
    }
    return groups;
}

// 格式化
function formatterFormData(formData: { [k: string]: any }): [BaseErr?, any?] {
    let { rows } = formData;
    let rowArray = Array.isArray(rows) ? rows : [];

    // 找到 top 栏
    let topRowIndex = getTopRowData(rowArray);
    if (util.nilValue(topRowIndex)) {
        return [new BaseErr(-4008, "表格头没找到"), undefined];
    }
    // top栏
    let topRowData = rowArray[topRowIndex!];
    let today = util.UTC8ConverDate(new Date());
    // 找到今天的index
    let todayIndex = findTodayIndex(topRowData, today);
    if (util.nilValue(todayIndex)) {
        let todayDes = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
        return [new BaseErr(-4008, `表格头里 没有今天 ${todayDes} 哦`), undefined];
    }
    // 格式化数据
    return [undefined, formatterGroupData(rowArray, topRowIndex!, todayIndex!)];
}

// 获取数据咯
function formatterContent(original: string | object): [BaseErr?, any?] {
    let jsonObj = formatter2Obj(original);
    if (util.nilValue(jsonObj)) {
        return [new BaseErr(-4005, "加密 数据转成json 失败"), undefined];
    }
    let { content = {} } = (jsonObj || {}) as any;
    let docData = content[DingInfo.docTable];
    if (util.nilValue(docData)) {
        return [new BaseErr(-4006, `没有目标 ${DingInfo.docTable} 表格的数据`), undefined];
    }
    // 处理数据
    return formatterFormData(docData);
}

export { formatterContent };
